package com.javajun.endofterm.controller;

import com.javajun.endofterm.entity.Menu;
import com.javajun.endofterm.service.DomitoryService;
import com.javajun.endofterm.service.ExpressDeliveryService;
import com.javajun.endofterm.service.MenuService;
import com.javajun.endofterm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-12-01-3:42 上午
 */
@Controller
public class HelloControler {

    @Autowired
    private StudentService studentService;

    @Autowired
    private DomitoryService domitoryService;

    @Autowired
    private ExpressDeliveryService expressDeliveryService;

    @Autowired
    private MenuService menuService;

    @GetMapping("/login")
    public String loginView() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String url = "";
        if (auth instanceof AnonymousAuthenticationToken) {
            url = "login";
        } else {
            Set<String> rolSet = AuthorityUtils.authorityListToSet(auth.getAuthorities());
            if (rolSet.contains("ROLE_ADMIN")) {
                url = "redirect:/main";
            } else if (rolSet.contains("ROLE_STUDENT")) {
                url = "redirect:/main";
            }
        }
        return url;
    }

    @RequestMapping("/main")
    public String mainView(ModelMap map) {

        return "main";
    }

    @RequestMapping(value = "/home")
    public String homeView() {
        return  "home";
    }

    @ResponseBody
    @RequestMapping(value = "/init.json", produces="application/json; charset=UTF-8")
    public Object homeJson() {
        Menu adminMenu = menuService.findByName("管理员");
        Menu studentMenu = menuService.findByName("学生");

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String menJson = "";
        Set<String> rolSet = AuthorityUtils.authorityListToSet(auth.getAuthorities());
        if (rolSet.contains("ROLE_ADMIN")) {
            menJson = adminMenu.getJson();
        } else if (rolSet.contains("ROLE_STUDENT")) {
            menJson = studentMenu.getJson();
        }
        return menJson;
    }

}
